package com.hyg.lib_music.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.DataModel.EventBusMessage;
import com.hyg.lib_common.DataModel.Music.Music;
import com.hyg.lib_common.DataModel.YangShengInfo.ReceiveDataInt;
import com.hyg.lib_common.Net.CommonHttpUtil;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_music.R;
import com.hyg.lib_music.databinding.ActivityTestingResultBinding;
import com.hyg.lib_music.modle.RecommedMusicData;
import com.hyg.lib_music.service.MusicService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class TestingResultActivity extends BaseActivity {
    String type;
    String result;
    List<RecommedMusicData.DataDTO> list;
    ActivityTestingResultBinding binding;
    ArrayList<Music> music_list = new ArrayList<>();
    int mark = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivityTestingResultBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        StatusBarUtil.setStatusBar(1, this, getResources().getColor(R.color.white), 60, null, null, true);
        init();
    }

    public void init() {
        type = getIntent().getStringExtra("type");
        result = getIntent().getStringExtra("result");
        if (!type.equalsIgnoreCase("1")) {
            mark = 3;
        }
        binding.tvResult.setText(result);
        binding.tvResultinfo.setText("\u3000\u3000根据您本次的检测结果[" + result + "]，我们为您定制了音乐疗愈，请根据自身情况使用。");
        saveResult(type, result);
    }

    public void onBack(View view) {
        finish();
    }

    public void onRetest(View view) {
        if (type.equalsIgnoreCase("1")) {
            startActivity(new Intent(this, TesttingTizhiActivity.class));
            finish();
        } else {
            startActivity(new Intent(this, TesttingXinliActivity.class));
            finish();
        }
    }

    public void saveResult(String type, String result) {
        CommonHttpUtil.saveMusicTestResult(this, mark, result, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ErrorDialog("服务器错误");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("lgb", "onResponse:saveResult=" + result);
                ReceiveDataInt dataInt = JSONObject.parseObject(result, ReceiveDataInt.class);
                if (dataInt.getCode() != 200) {
                    Log.i("lgb", "onResponse: 提交结果失败 message====" + dataInt.getMessage());
                } else {
                    initData();
                }
            }
        });
    }

    private void initData() {
        CommonHttpUtil.getHealthMusic(this, mark, 0, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("lgb", "run: "+e.getMessage());
                        ErrorDialog("服务器错误");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("lgb", "onResponse initData: " + result);
                parseData(result);
            }
        });
    }


    public void parseData(String data) {
        RecommedMusicData musicData = JSONObject.parseObject(data, RecommedMusicData.class);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (musicData.getCode() == 200) {
                    initPlayerView(musicData);
                } else {
                    ErrorDialog(musicData.getMessage());
                }
            }
        });
    }

    private void initPlayerView(RecommedMusicData musicData) {
        list = musicData.getData();
        binding.itemControl1.cvRoot.setVisibility(View.VISIBLE);
        if (type.equalsIgnoreCase("1")) {
            binding.itemControl1.ivControlImage.setImageResource(R.mipmap.yangsheng_music_icon);
            binding.itemControl1.tvControlTitle.setText("养生定制方案");
            EventBus.getDefault().post(new EventBusMessage("updateYSdata"));
        } else {
            binding.itemControl1.ivControlImage.setImageResource(R.mipmap.jieya_music_icon);
            binding.itemControl1.tvControlTitle.setText("解压定制方案");
            EventBus.getDefault().post(new EventBusMessage("updateXLdata"));
        }

        long sum=0;
        for(RecommedMusicData.DataDTO dataDTO:list){
            sum+=dataDTO.getMusicDuration();
        }
        music_list.clear();
        if (type.equalsIgnoreCase("1")) {
            MusicMainActivity.serviceBinder.setImagePath(R.mipmap.yangsheng_music_icon);
            for (RecommedMusicData.DataDTO dataDTO : list) {
                music_list.add( new Music(dataDTO.getId(), dataDTO.getMusicName(), dataDTO.getMusician(), dataDTO.getMusicDuration(),
                        dataDTO.getRegion(), dataDTO.getMusicUrl(), (dataDTO.getFavorite()==1),
                        1,0, result,
                        (MusicMainActivity.serviceBinder.isPlaying() && MusicMainActivity.serviceBinder.getCurrentMusic().musicName.equals(dataDTO.musicName)),
                        false,false));
            }
        } else {
            MusicMainActivity.serviceBinder.setImagePath(R.mipmap.jieya_music_icon);
            for (RecommedMusicData.DataDTO dataDTO : list) {
                music_list.add( new Music(dataDTO.getId(), dataDTO.getMusicName(), dataDTO.getMusician(), dataDTO.getMusicDuration(),
                        dataDTO.getRegion(), dataDTO.getMusicUrl(), (dataDTO.getFavorite()==1),
                        3,0, result,
                        (MusicMainActivity.serviceBinder.isPlaying() && MusicMainActivity.serviceBinder.getCurrentMusic().musicName.equals(dataDTO.musicName)),
                        false,false));
            }
        }
        binding.itemControl1.tvControlIntro.setText((sum/60+1)+"min");
        binding.itemControl1.lnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicMainActivity.result_type = result;
                MusicMainActivity.serviceBinder.addPlayList(music_list, music_list.get(0));
            }
        });
        binding.itemControl1.rlMusicControl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (list != null && list.size() > 0) {
                    Intent intent = new Intent(TestingResultActivity.this, PlayingListActivity.class);
                    intent.putParcelableArrayListExtra("data", music_list);
                    startActivity(intent);
                } else {
                    Toast.makeText(TestingResultActivity.this, "未发现音乐列表！", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }



    @Subscribe
    public void onEvent(EventBusMessage message) {
     if(message.getmessage().equals(Constants.Add_Favorite)){
            for(Music music:music_list){
                if( music.id==message.getMusicId()){
                    music.isFav=true;
                }
            }
        }else if(message.getmessage().equals(Constants.Cancel_Favorite)){
            for(Music music:music_list){
                if( music.id==message.getMusicId()){
                    music.isFav=false;
                }
            }
        }
    }

    @Override
    public void finish() {
        super.finish();
        EventBus.getDefault().unregister(this);
    }
}